package com.zoe.onelink.core.validation.impl;

import cn.hutool.core.collection.CollUtil;
import com.zoe.onelink.core.web.validation.resolver.ValidationFieldInfoManager;
import com.zoe.onelink.enhancer.scanner.AbstractClassScanner;
import io.swagger.annotations.ApiModelProperty;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.BeanFactory;

import java.lang.reflect.Field;
import java.util.Set;

/**
 * <p>标题: </p>
 * <p>描述: </p>
 * <p>版权: Copyright (c) 2021</p>
 * <p>公司: 智业软件股份有限公司</p>
 *
 * @version: 1.0
 * @author: ruansheng
 * @date: 2021-11-30
 */
@Slf4j
public class ValidationFieldInfoScanner extends AbstractClassScanner {

    private static final String PARAM_CLASS_SUFFIX = "Param";

    public ValidationFieldInfoScanner(BeanFactory beanFactory) {
        super(beanFactory);
    }

    @Override
    protected void doInvoke(Set<? extends Class<?>> classes) {
        if (CollUtil.isEmpty(classes)) {
            return;
        }
        for (Class<?> clazz : classes) {
            String className = clazz.getName();
            if (!className.endsWith(PARAM_CLASS_SUFFIX)) {
                continue;
            }

            try {
                Field[] declaredFields = clazz.getDeclaredFields();
                for (Field field : declaredFields) {
                    ApiModelProperty apiModelProperty = field.getAnnotation(ApiModelProperty.class);
                    if (apiModelProperty == null) {
                        continue;
                    }
                    ValidationFieldInfoManager.putFieldDesc(className, field.getName(), apiModelProperty.value());
                }
            } catch (Throwable throwable) {
                log.error("Parse validation info of swagger-annotation failure");
            }
        }
    }

}
